package deom2;

import java.util.Arrays;

public class MyArrayList implements ISeqList {

    final int SIZE =10;
    int[] myArrayList = new int[SIZE];
    int useData = 0;

    private int[] expansion(int[] arr) {
        return Arrays.copyOf(arr,arr.length*2);
    }

    private int findData(int data) {
        for (int i = 0; i < useData; i++) {
            if(myArrayList[i] == data) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public void print() {
        System.out.print("[");
        for(int i = 0; i < useData; i++) {
            System.out.print(myArrayList[i]+(i == useData - 1 ? "" : ","));
        }
        System.out.print("]");
        System.out.println();
    }

    @Override
    public void addData(int data) {
        if(useData == myArrayList.length) {
            myArrayList = expansion(myArrayList);
        }
        myArrayList[useData] = data;
        useData++;
    }

    @Override
    public void addPosData(int data, int pos) throws PosException {
        if(pos < 0 || pos > useData) {
            throw new PosException("pos 位置不合法");
        }
        if(useData == myArrayList.length) {
            myArrayList = expansion(myArrayList);
        }
        int tem = useData;
        while (tem > pos) {
            myArrayList[tem] = myArrayList[tem - 1];
            tem--;
        }
        myArrayList[tem] = data;
        useData++;
    }

    @Override
    public void delData(int pos) throws ArrayIsEmpty,PosException {
        if(pos < 0 || pos >= useData) {
            throw new PosException("pos 位置不合法");
        }
        if(useData == 0) {
            throw new ArrayIsEmpty("顺序表空了");
        }
        int tem = pos;
        while (tem < useData - 1) {
            myArrayList[tem] = myArrayList[tem + 1];
            tem++;
        }
        useData--;
    }

    @Override
    public int returnData(int pos) throws ArrayIsEmpty {
        if(useData == 0) {
            throw new ArrayIsEmpty("顺序表空了");
        }
        return myArrayList[pos];
    }

    @Override
    public int returnPos(int data) throws ArrayIsEmpty {
        if(useData == 0) {
            throw new ArrayIsEmpty("顺序表空了");
        }
        if(findData(data) != -1) {
            return findData(data);
        }
        System.out.println("找不到");

        return -1;
    }

    @Override
    public void setPosData(int value, int pos) throws PosException {
        if(pos < 0 || pos >= useData) {
            throw new PosException("pos 位置不合法");
        }
        myArrayList[pos] = value;
    }


    @Override
    public void clean() {
        useData = 0;
    }
}
